import java.util.Objects;



public class HashBucket {
    static class Node {
        private int key;
        private int value;
        private Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    public Node[] array;
    public int usedSize;
    //默认负载因子为0.75
    private static final float DEFAULT_FACTOR = 0.75f;

    public HashBucket() {
        this.array = new Node[10];
    }

    public void put(int key,int val) {
        Node node = new Node(key,val);
        int index = key% array.length;
        //遍历Index位置下方的链表
        Node cur = array[index];

        while(cur != null) {
            if(cur.key == key) {
                cur.value = val;
                return;
            }
            cur = cur.next;
        }
        //cur == null ,没有这个key，那么进行头插
        node.next = array[index];
        array[index] = node;


        usedSize++;
        //计算负载因子
        if(loadFactor() >= DEFAULT_FACTOR) {
            //扩容
            resize();
        }

    }

    //重新哈希原来的数据
    private void resize() {
        //2倍扩容
        Node[] tempArray = new Node[array.length *2];
        //遍历原来的数组下标的每一链表
        for(int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null) {
                //需要记录下来原链表当前位置的下一个位置，否则头插后，就找不到下一个结点了
                Node curNext = cur.next;
                int index = cur.key % tempArray.length;//新数组的位置
                //采用头插法，放到新数组的位置
                cur.next = tempArray[index]; //这里修改后 cur的next已经变了
                tempArray[index] = cur;
                cur = curNext;

            }
        }
        array = tempArray;
    }

    private float loadFactor() {
        return usedSize*1.0f / array.length;
    }

    /**
     * 通过key值返回value
     *
     */
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }



    public static void main1(String[] args) {
        HashBucket hashBucket = new HashBucket();
        hashBucket.put(1,49);
        hashBucket.put(2,26);
        hashBucket.put(12,85);
        hashBucket.put(3,36);
        hashBucket.put(4,23);
        hashBucket.put(14,11);
        hashBucket.put(5,78);
        hashBucket.put(16,23);
        System.out.println(hashBucket.get(16));
        System.out.println();
    }

}
